<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="expires" content="no-cache">
<title>Insert title here</title>
<%
	//防止浏览器产生缓存
	response.setHeader("Pragma","No-Cache"); 
	response.setHeader("Cache-Control","No-Cache"); 
	response.setDateHeader("Expires", 0); 

	//定义基础路径，从DispatcherServlet获取数据
	String path = request.getContextPath() + "/";	
	String resourcesPath = path + "resources/";
	String omPath = resourcesPath + "operamasks-ui-2.0/";		
	
%>
<link href="<%=omPath%>css/default/om-default.css" rel="stylesheet"	type="text/css" />
<script src="<%=omPath%>js/jquery.min.js" type="text/javascript"></script>
<script src="<%=path%>resources/sm/js/jquery.xml2json.js" type="text/javascript"></script>
<script src="<%=omPath%>js/operamasks-ui.min.js" type="text/javascript"></script>
<script src="<%=path%>resources/sm/js/om-dialog-url.js" type="text/javascript"></script>
<style type="text/css">
	.color_red { color: red; }
	.search-button{
	padding-left: 30px;
	padding-top: 9px;
	}
	
   	.myinput input{
    border:1px solid;
    border-color:lightblue;
    height: 18px;
    width : 160px;
   	}
   	.myinput input:focus{border: 1px solid #3A76C2;}
   	input.error{border: 1px solid red;}
 	.mytable td{
   	padding-top: 5px;
   	}
   .mytable .mytable-left{
   text-align: right;
   width : 100px;
   }
  .mytable .mytable-right{
   width : 150px;
   }
</style>
<script type="text/javascript">
//集中获取ModelAndView数据
var path = "${pageContext.request.contextPath}" + "/";
//定义全局变量
var validator = null;
var dialogType;// 对话框类型：增加，删除，修改

var grid = null; // 生成表格
var searchFiled = null;// 生成搜索字段
var serchButton = null;// 生成搜索按钮
var mainTool = null;// 生成工具栏
var dialogAdd = null;// 生成添加对话框
var addForm = null; // 生成添加表单
var dialogMatReq = null; // 生成申请对话框
var reqSendTime = null;// 生成发运时间
var inputHelper = null;
var divInputChooser = null;// 生成输入选择框

// 设置表格操作提交的网址
var searchUrl = path + "rm/filterQuery.html";
var addUrl = path + "rm/gridAdd.html";
var deleteUrl = path + "rm/gridDelete.html";
var editUrl = path + "rm/gridEdit.html";
var matReqUrl = path + "rm/MatReqCtl/matReq.html";
var undoMatReqUrl = path + "rm/MatReqCtl/undoMatReq.html";


$(function() {
	initVars();
	loadLayout();// 加载布局
	loadGrid();// 加载表格
	loadSearchPanel();// 加载搜索面板
	loadButtonBar();// 加载工具栏
	loadInputHelperButton();
	loadDialogAdd();// 加载对话框-增加
	loadDialogMatReq();// 加载对话框-要料申请
	search();// 搜索
});

function initVars(){
	// 集中定义jQuery选择器
	grid =$('#maingrid'); // 生成表格
	searchFiled = $('#search-field');// 生成搜索字段
	serchButton = $('#search-button'); // 生成搜索按钮
	mainTool = $('#maintool'); // 生成工具栏
	dialogAdd = $('#dialog-Add'); // 生成添加对话框
	addForm = $('#addForm'); // 生成添加表单
	dialogMatReq = $('#dialog-MatReq'); // 生成申请对话框
	reqSendTime = $('#reqSendTime');// 生成发运时间
	inputHelper = $('#inputHelper');
	divInputChooser = $('#divInputChooser');
}

function loadLayout(){
	$('#page').omBorderLayout({
		panels : [ {
			id : "center-panel",
			header : false,
			region : "center"
		} ]
	});
	$('#search-panel').omPanel({
		title : "搜索",
		collapsible : true,
		height : 155
	});
}

function loadGrid(){
	grid.omGrid(
			{
				limit: 30,
				singleSelect: false,
		        title : '要料申请',
		        height:500,
		        colModel : [
						{header : '要料单号', name : 'reqId', align : 'center', width : '130', sort:'serverSide'},
						{header : '要求发运日期', name : 'reqSendTime', align : 'center', width : '140', sort:'serverSide'},
						{header : '物料编码', name : 'materialId', align : 'center', width : '130', sort:'serverSide'},
						{header : '物料描述', name : 'materialDesc', align : 'center', width : '240', sort:'serverSide'},
						{header : '需求量(KG)', name : 'netWeight', align : 'center', width : '100', sort:'serverSide'},
						{header : '处理状态', name : 'uploadStatus', align : 'center', width : '100',
							renderer : function(colValue, rowData, rowIndex) {
								switch(colValue){
								case 'N':return "未发送";
								case 'Y':return "已发送";
								case 'C':return "已取消";
								}
							}
						},
						{header : '上传时间', name : 'uploadTime', align : 'center', width : '140', sort:'serverSide'},
						{header : '物流状态', name : 'logisticsStatus', align : 'center', width : '100', sort:'serverSide',
							renderer : function(colValue, rowData, rowIndex) {
								switch(colValue){
								case 'NOT':return "未发货";
								case 'IN':return "已发货";
								case 'RECEIVE':return "已收货";
								case 'RETURN':return "已退货";
								default:return "未发货";
								}
							}	
						},
		                    ],
			}
			);
}

//加载搜索面板
function loadSearchPanel() {
	$('#search-field input').each(function() {
		$(this).keyup(function(event) {
			if (event.keyCode == 13) {
				search();
			}
		});
	});
	
	$('#queryUploadStatus').omCombo({
		dataSource : [ {
			text : '未发送',
			value : 'N'
		}, {
			text : '已发送',
			value : 'Y'
		} , {
			text : '已取消',
			value : 'C'
		} ],
		editable : false,
		inputField:function(data,index){
		    return data.text+'('+data.value+')';
		},
		value : 'N',
		width : 150
	});
	$("#queryUploadTimeS").omCalendar({showTime : true});
	$("#queryReqSendTimeS").omCalendar({showTime : true});
	$("#queryReqSendTimeE").omCalendar({showTime : true});
	$("#queryUploadTimeS").css("width","140px");
	$("#queryReqSendTimeS").css("width","140px");
	$("#queryReqSendTimeE").css("width","140px");
	// 加载搜索按钮
	serchButton.omButton({
		icons : {
			left : path + 'resources/sm/images/search.png'
		},
		width : 70,
		onClick : function(event) {
			if ($("#queryUploadStatus", searchFiled).val() == "C") {
				mainTool.hide();
			} else {
				mainTool.show();
			}
			search();
		}
	});
}

function search()
{	
	var rules =[], i=0;
	$(':input','#searchTable').each(function() {
		if($.trim(this.name)!="")
			if( $(this).val() != null &&  $.trim($(this).val()) != "" 
					&& typeof($(this).attr('op')) != "undefined" && typeof($(this).attr('ty')) != "undefined")
				rules[i++] = {op : $(this).attr('op'), field : $(this).attr('name'), value : $(this).val(), type : $(this).attr('ty')};
	});
	var group ={
			op : "and",
			rules : rules
	};
	var extraData = {
			"domain" : "SmRmMaterialRequest",
			"rules" : i==0?null:JSON.stringify(group),
	};
	grid.omGrid({
		dataSource : searchUrl,
		extraData : extraData, 
		method:'POST'
	}, 'reload');
	var state = $('#queryUploadStatus', searchFiled).omCombo('value');
	if (state == "N") {
		$("#grid-add", mainTool).parent().parent().show();
		$("#grid-delete", mainTool).parent().parent().show();
		$("#grid-edit", mainTool).parent().parent().show();
		$("#mat-Req", mainTool).parent().parent().show();
		$("#mat-Cancel", mainTool).parent().parent().hide();
	} else if (state == "Y") {
		$("#grid-add", mainTool).parent().parent().hide();
		$("#grid-delete", mainTool).parent().parent().hide();
		$("#grid-edit", mainTool).parent().parent().hide();
		$("#mat-Req", mainTool).parent().parent().hide();
		$("#mat-Cancel", mainTool).parent().parent().show();
	}
};

//加载工具栏
function loadButtonBar() {
	var buttons = [ {
		label : "增加",
		id : "grid-add",
		onClick : function() {
			addForm.clearForm();
			dialogType = 'add';
			showDialogAdd('新增记录', null);
		}
	}, {
		separtor : true
	}, {
		label : "删除",
		id : "grid-delete",
		onClick : function() {
			var selectedRows = grid.omGrid('getSelections', true);
			if (selectedRows && selectedRows.length > 0) {
				$.omMessageBox.confirm(
				{
					title: "提示",
					content: "确定要删除选中记录?",
					onClose: function( value )
					{
						if( value ) gridDelete( selectedRows );
					}
				});
			} else {
				$.omMessageBox.alert({
					content : '请至少选择一行记录！',
				});
			}
		}
	}, {
		separtor : true
	}, {
		label : "修改",
		id : "grid-edit",
		onClick : function() {
			var selections = grid.omGrid('getSelections', true);
			if (selections.length != 1) {
				$.omMessageBox.alert({
					content : '请选择一行记录',
				});
			} else {
				dialogType = 'edit';
				showDialogAdd('修改记录', selections[0]);
			}
		}
	}, {
		separtor : true
	}, {
		label : "发送要料申请",
		id : "mat-Req",
		onClick : function() {
			var selections = grid.omGrid('getSelections', true);
			if (selections.length > 0) {
				showDialogMatReq('发送要料申请');
			} else {
				$.omMessageBox.alert({
					content : '请至少选择一行记录',
				});
			}
		}
	}, {
		separtor : true
	}, {
		label : "取消要料申请",
		id : "mat-Cancel",
		onClick : function() {
			var selections = grid.omGrid('getSelections', true);
			if (selections.length > 0) {
				$.omMessageBox.confirm(
				{
					title: "提示",
					content: "确定要取消选中的申请单?",
					onClose: function( value )
					{
						if( value ) undoMatReq( selections );
					}
				});
			} else {
				$.omMessageBox.alert({
					content : '请至少选择一行记录',
				});
			}
		}
	} ];
	var btnBarCfg = {
		btns : buttons
	};
	mainTool.omButtonbar(btnBarCfg);
}

function loadInputHelperButton(){
	
	var selectUrl = path + "sm/select-input.html?jspName=sm/rm/matChooser";
	var frameId = "AnaInput";
	var buttons = [ {
		text : "关闭",
		click : function() {
			divInputChooser.omDialog("close");// 关闭dialog
		}
	} ];
	divInputChooser.omDialog({
		width : 600,
		height : 470,
		autoOpen : false,
		modal : true,
		resizable : false,
		targetmode : "iframe",
		name : frameId,
		url : selectUrl,
		buttons : buttons,
	});

	$('#materialId','#addForm').keydown(function(e){
        if(e.keyCode==118){ //如果按的键是F7
        	inputHelper.omButton('click');
            return false;
        }else{
            return false; //禁用输入其它内容
        }
    });
	
	$('#netWeight','#addForm').keydown(function(e){
        if(e.keyCode==13){ 
        	$('#sure').click();
            return false;
        }
    });
	
	inputHelper.omButton({
		width : 35,
		id : "inputHelperBtn",
		onClick : function(event){
			divInputChooser.omDialog("option", "title", "选择（双击记录即可选择）");
			divInputChooser.omDialog("open");// 显示dialog
			var childWindow = document.getElementById(frameId).contentWindow;
			childWindow.search();
        }
	});
	
}

function fillBackAndCloseDialog(rowData) {
	$("#materialId" , $("#addForm")).val(rowData["materialId"]);
	$("#materialDesc", $("#addForm")).val(rowData["materialDesc"]);
	divInputChooser.omDialog("close");
};

//加载新增对话框
function loadDialogAdd() {
	var buttons = [ {
		text : '确定',
		id:'sure',
		click : function() {
			switch (dialogType) {
			case 'add':
				gridAdd();
				break;
			case 'edit':
				gridEdit();
				break;
			default:
				break;
			}
		}
	}, {
		text : '取消',
		click : function() {
			dialogAdd.omDialog("close");
		}
	} ];
	dialogAdd.omDialog({
		width : 400,
		height : 280,
		autoOpen : false,
		resizable : false,
		modal : true,
		buttons : buttons,
		onClose : function(){
			$(':input',addForm).each(function(){
				if(typeof($(this).attr('id')) != "undefined" && typeof($(this).attr('name')) != "undefined"){
					$(this).omTooltip('hide');
				}
			});
		}
	});
	$('#netWeight','#addForm').omNumberField({allowDecimals : true});
	validateInit();
	// 显示dialog并初始化里面的输入框的数据
	showDialogAdd = function(title, rowData) {
		validator.resetForm();
		if(rowData==null)
		{
			rowData={};
		}
		else
		{
		    $('#addForm input').each(function(){
		    	$(this,dialogAdd).val(rowData[this.name]);
			});
		}
		dialogAdd.omDialog("option", "title", title);
		dialogAdd.omDialog("open");// 显示dialog
	};
}

function validateInit()
{
	validator = $("#addForm").validate(
			{
				//编写验证规则
				rules: {
					materialId: { required: true },
					materialDesc: { required: true },
					netWeight: { required: true, digits: true },
					},
				messages: {
					materialId: { required: "" },
					materialDesc: { required: "" },
					netWeight: { required: "" },
					},
			});
	
	$('#materialId').omTooltip({
		  region : 'right',
       html : '不能为空！',
       anchor : true ,
       offset : [-5,45]
	});
	$('#materialDesc').omTooltip({
		  region : 'right',
     html : '不能为空！',
     anchor : true ,
     offset : [-5,5]
	});
	$('#netWeight').omTooltip({region : 'right', html : '非空，必须为数字，长度不超6位！', anchor : true , offset : [-5,5]});
	
}

function getSubmitData(form)
{
	var info = {};
	$(':input',form).each(function(){
		if(typeof($(this).attr('id')) != "undefined" && typeof($(this).attr('name')) != "undefined"){
			info[$(this).attr('id')] = $(this).val();
		}
	});

	return JSON.stringify(info);
}

function gridAdd(){
	if(validator.form()){
		var info = {
				"domain" : "SmRmMaterialRequest",
				"SmRmMaterialRequest" : getSubmitData(addForm)
		};
		$.post( addUrl,info, 
				function(data, textStatus)
				{
			     if( data.success )
					{
			    	 $.omMessageBox.alert( { type: "success", title:"成功", content: data.message } );
			    	 grid.omGrid( "reload" );
					}
			     else
			    	 {
						$.omMessageBox.alert( { type: "error", title:"失败", content: data.message } );
			    	 }						
				});
		dialogAdd.omDialog("close");
	}else{
		
		$(':input',addForm).each(function(){
			if(typeof($(this).attr('id')) != "undefined" && typeof($(this).attr('name')) != "undefined"){
				$(this).omTooltip('show');
			}
		});
	}
}
function gridEdit(){
	if(validator.form()){
		var data = grid.omGrid('getSelections', true)[0];
		$(':input',addForm).each(function(){
			if(typeof($(this).attr('id')) != "undefined" && typeof($(this).attr('name')) != "undefined"){
				data[$(this).attr('id')] = $(this).val();
			}
		});
		var info = {
				"domain" : "SmRmMaterialRequest",
				"SmRmMaterialRequest" : JSON.stringify(data)
		};
		$.post( editUrl,info, 
				function(data, textStatus)
				{
			     if( data.success )
					{
			    	 $.omMessageBox.alert( { type: "success", title:"成功", content: data.message } );
			    	 grid.omGrid( "reload" );
					}
			     else
			    	 {
						$.omMessageBox.alert( { type: "error", title:"失败", content: data.message } );
			    	 }						
				});
		dialogAdd.omDialog("close");
	}
}

function gridDelete(rows){
	var params = "";
	
	for( var i=0; i<rows.length; i++ )
	{
		var rowData = rows[i];
		if(i!=0){
			params += ( ","+rowData["id"]);
		}else{
			params += ( rowData["id"]);
		}
	}
	if( params.length > 0)
	{
		var info = {
				"domain" : "SmRmMaterialRequest",
				"ids" : params
		};
		$.post( deleteUrl,info,
				function(data, textStatus)
				{
			     if( data.success )
					{
			    	 	$.omMessageBox.alert( { type: "success", title:"删除成功", content: data.message } );
			    	 	grid.omGrid( "reload" );
					}
			     else
			    	 {
						$.omMessageBox.alert( { type: "error", title:"删除失败", content: data.message } );
			    	 }						
				}
				, "json" 
				);
	}
}

function loadDialogMatReq() {
	reqSendTime.omCalendar({
		showTime : true,
		editable : false,
		disabledFn : function disFn(date) {
	        var nowMiddle = new Date();
	        if (date < nowMiddle) {
	            return false;
	        }
		}
	});
	var buttons = [ {
		text : '确定',
		click : function() {
			var selections = grid.omGrid('getSelections', true);
			var sendTime = reqSendTime.val();
			if (sendTime != '') {
				matReq(selections, sendTime);
				//var now = (new Date()).toLocaleString();
			} else {
				$.omMessageBox.alert({
					type : 'error',
					title : '失败',
					content : '要求送料时间不能为空并且要大于当前系统时间'
				});
			}
		}
	}, {
		text : '取消',
		click : function() {
			dialogMatReq.omDialog("close");
		}
	} ];
	dialogMatReq.omDialog({
		width : 400,
		height : 100,
		autoOpen : false,
		resizable : false,
		modal : true,
		buttons : buttons
	});
	// 显示dialog并初始化里面的输入框的数据
	showDialogMatReq = function(title) {
		dialogMatReq.omDialog("option", "title", title);
		dialogMatReq.omDialog("open");// 显示dialog
	};
}
function matReq(selections, sendTime) {
	var info = {
		"reqSendTime" : sendTime,
		"selectedRows" : JSON.stringify(selections)
	};
	$.post( matReqUrl,info,
			function(data, textStatus)
			{
		     if( data.success )
				{
		    	 dialogMatReq.omDialog("close");	
		    	 $.omMessageBox.alert( { type: "success", title:"发送成功", content: data.message } );
		    	 	grid.omGrid( "reload" );
		    	 	reqSendTime.val('');
				}
		     else
		    	 {
					$.omMessageBox.alert( { type: "error", title:"发送失败", content: data.message } );
		    	 }						
			}, "json");
}
function undoMatReq(selections) {
	var info = {
		"selectedRows" : JSON.stringify(selections)
	};
	$.post( undoMatReqUrl,info,
			function(data, textStatus)
			{
		     if( data.success )
				{
		    	 	$.omMessageBox.alert( { type: "success", title:"取消成功", content: data.message } );
		    	 	grid.omGrid( "reload" );
				}
		     else
		    	 {
					$.omMessageBox.alert( { type: "error", title:"取消失败", content: data.message } );
		    	 }						
			}, "json");
}
</script>

</head>
<body id="mainBody">	
	<div id="page" style="height:690px;">
		<div id="center-panel">
			<div id="search-panel">
				<div id="search-field">
				<table id="searchTable" class="mytable">
					<tr>
						<td class="mytable-left"><span><font face="微软雅黑" size="2px" color="darkblue">要料单号:</font></span></td>
						<td class="mytable-right"><span class="myinput"><input id="queryReqId" name="reqId" op="startwith" ty="string" type="text" /></span></td>
						<td class="mytable-left"><span><font face="微软雅黑" size="2px" color="darkblue">物料编码:</font></span></td>
						<td class="mytable-right"><span class="myinput"><input id="queryMaterialId" name="materialId" op="startwith" ty="string" type="text" /></span></td>
						<td class="mytable-left"><span><font face="微软雅黑" size="2px" color="darkblue">物料描述:</font></span></td>
						<td class="mytable-right"><span class="myinput"><input id="queryMaterialDesc" name="materialDesc" op="like" ty="string" type="text" /></span></td>
						<td class="mytable-left"><span><font face="微软雅黑" size="2px" color="darkblue">处理状态:</font></span></td>
						<td class="mytable-right"><span class="myinput"><input id="queryUploadStatus" name="uploadStatus" op="equal" ty="string" type="text" /></span></td>
					</tr>
					<tr>
						<td class="mytable-left"><span><font face="微软雅黑" size="2px" color="darkblue">发送时间从:</font></span></td>
						<td class="mytable-right"><span class="myinput"><input id="queryUploadTimeS" name="uploadTime" op="greaterorequal" ty="date" type="text" /></span></td>
						<td class="mytable-left"><span><font face="微软雅黑" size="2px" color="darkblue">要求发运时间从:</font></span></td>
						<td class="mytable-right"><span class="myinput"><input id="queryReqSendTimeS" name="reqSendTime" op="greaterorequal" ty="date" type="text" /></span></td>
						<td class="mytable-left"><span><font face="微软雅黑" size="2px" color="darkblue">要求发运时间到:</font></span></td>
						<td class="mytable-right"><span class="myinput"><input id="queryReqSendTimeE" name="reqSendTime" op="lessorequal" ty="date" type="text" /></span></td>
					</tr>
				</table>
				</div>
				<div class="search-button"><span id="search-button">搜索</span></div>
			</div>
			<div id="maintool"></div>
			<table id="maingrid"></table>
		</div>    	
	</div>	
    <div id="dialog-Add">	
		<form id="addForm">
		<table class=mytable>
			<tr>
				<td class="mytable-left"><span class="label" style="color:darkblue">物料编码:</span></td>
				<td id="materialId-td" class="mytable-right"><span class="myinput"><input
						id="materialId" name="materialId" class='text' type="text" readonly="readonly"/></span></td>
				<td><button id='inputHelper' value="浏览"></button></td>
			</tr>
			<tr>
				<td class="mytable-left"><span class="label" style="color:darkblue">物料描述:</span></td>
				<td id="materialDesc-td" class="mytable-right"><span class="myinput"><input
						id="materialDesc" name="materialDesc" class='text' type="text" readonly="readonly"/></span></td>
			</tr>
			<tr>
				<td class="mytable-left"><span class="label" style="color:darkblue">需求量(KG):</span></td>
				<td id="netWeight-td" class="mytable-right"><span class="myinput"><input
						id="netWeight" name="netWeight" class='text' type="text" maxlength="6"/></span></td>
			</tr>
			<tr>
				<td id="id-td"><input id="id" name="id" type="hidden" /></td>
			</tr>
		</table>
		</form>	
	</div>
	<div id="dialog-MatReq">
		<label>要求发运时间：</label>
		<input id="reqSendTime"></input>
	</div>
	<div id = "divInputChooser"></div>
</body>
</html>